package com.lcn.tm.service.db;

import com.lcn.comm.domain.TxGroup;
import com.lcn.comm.domain.TxRequest;
import com.lcn.comm.service.db.DataSourceService;
import com.lcn.comm.service.redis.RedisService;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017-12-27 10:13
 */
@MotanService
public class DataSourceServiceImpl implements DataSourceService {

    @Resource
    private RedisService redisService;

    /**
     * 根据groupId,requestId检查事务状态
     *
     * @param groupId
     * @param requestId
     * @return
     */
    public int cleanNotifyTransaction(String groupId, String requestId) {
        int res = 0;
        TxGroup txGroup = redisService.getTxGroupByKey(groupId);
        if (txGroup == null || txGroup.isHasOver()) {
            return res;
        }

        //更新数据
        for (TxRequest txRequest : txGroup.getList()) {
            if (StringUtils.equals(txRequest.getRequestId(), requestId)) {
                if (!txRequest.isNotify()) {
                    txRequest.setNotify(true);
                    //保存记录
                    redisService.setValue(groupId, txGroup);
                    res = 1;
                    break;
                }
            }
        }

        //判断是否全部通知，如果全部通知，则直接结束事务
        boolean isOver = true;
        for (TxRequest txRequest : txGroup.getList()) {
            if (!txRequest.isNotify()) {
                isOver = false;
            }
        }

        if (isOver) {
            redisService.remove(groupId);
        }
        return res;
    }
}
